<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
</head>
<body  class="layui-anim layui-anim-up">
<div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>定时任务</cite>
        </a>
      </span>
</div>

<div class="x-body">
    <xblock>
    	<button class="layui-btn layui-btn-normal" id="reload"><i class="layui-icon">&#xe669;</i>刷新</button>
        <!-- <button class="layui-btn layui-btn-warm" id="add"><i class="layui-icon layui-icon-delete"></i>新增邮件定时任务</button> -->
        <button class="layui-btn layui-btn-warm" id="edit"><i class="layui-icon">&#xe642;</i>编辑</button>
    </xblock>
</div>
<table class="layui-hide" id="LAY_table_user" lay-filter="user"></table>


<div id="addDivID" hidden="hidden">
    <form class="layui-form" id="addFormID">
    	<br>
    	<br>
        <input hidden id="id" name="id">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">任务组名称</label>
                <div class="layui-input-inline">
                    <input class="layui-input" type="text" id="jobGroupName" name="jobGroupName" lay-verify="required" style="width: 375px">
                    <span class="xing" style="margin-left: 390px;font-size: 24px;"></span>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">任务名称</label>
                <div class="layui-input-inline">
                    <input class="layui-input" type="text" id="jobName" name="jobName" lay-verify="required" style="width: 375px">
                    <span class="xing" style="margin-left: 390px;font-size: 24px;"></span>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">定时</label>
                <div class="layui-input-inline">
                    <input class="layui-input" type="text" id="cronExpression" name="cronExpression" lay-verify="cronExpression" style="width: 375px">
                    <span class="xing" style="margin-left: 390px;font-size: 24px;"></span>
                </div>
            </div>
        </div>
        <button type="button" class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm" style="margin-left:180px;">提交</button>
        &emsp;&emsp;&emsp;&emsp;
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    </form>
</div>
<script>
    layui.use(['table','layer','upload','form','laydate'], function(){
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;

        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        
        
        //方法级渲染
        table.render({
            elem: '#LAY_table_user'
            ,url: '${pageContext.request.contextPath }/systemTask/list.do'
            ,cols: [[ //表头
                {type: 'checkbox', fixed: 'left'}
                ,{field:'', title:'序号', sort: true, type:'numbers', width: 60}
                ,{field: 'jobGroupName', title: '任务组名称'}
                ,{field: 'jobName', title: '定时任务名称', sort: true}
                ,{field: 'cronExpression', title: '时间表达式', width:180}
                ,{field: 'previousFireTime', title: '上次运行时间', width: 177,
                    templet: function (value, row, index){

                        value = value.previousFireTime
                        if (value == null || value == '') {
                            return '';
                        }
                        var dt;
                        if (value instanceof Date) {
                            dt = value;
                        } else {
                            dt = new Date(value);
                        }

                        return dt.format("yyyy-MM-dd hh:mm:ss"); //扩展的Date的format方法(上述插件实现)
                    }
                }
                ,{field: 'nextFireTime', title: '下次运行时间', width: 180,
                    templet: function (value, row, index){

                        value = value.nextFireTime
                        if (value == null || value == '') {
                            return '';
                        }
                        var dt;
                        if (value instanceof Date) {
                            dt = value;
                        } else {
                            dt = new Date(value);
                        }

                        return dt.format("yyyy-MM-dd hh:mm:ss"); //扩展的Date的format方法(上述插件实现)
                    }
                }
                ,{field: 'jobStatus', title: '任务状态', width: 180,  templet: function (value, row, index){
                        value = value.jobStatus

                        if (!value) {
                            return '';
                        }
                        if (value == 'NONE') {
                            return '未知';
                        } else if (value == 'NORMAL') {
                            return '正常运行';
                        } else if (value == 'PAUSED') {
                            return '暂停状态';
                        } else if (value == 'COMPLETE') {
                            return '完成状态';
                        } else if (value == 'ERROR') {
                            return '错误状态';
                        } else if (value == 'BLOCKED') {
                            return '锁定状态';
                        }

                    }  }
                ,{field: 'startTime', title: '开始时间', width: 180,
                    templet: function (value, row, index){

                        value = value.startTime
                        if (value == null || value == '') {
                            return '';
                        }
                        var dt;
                        if (value instanceof Date) {
                            dt = value;
                        } else {
                            dt = new Date(value);
                        }

                        return dt.format("yyyy-MM-dd hh:mm:ss"); //扩展的Date的format方法(上述插件实现)
                    }
                }
                ,{field: 'endTime', title: '结束时间', width: 235, sort: true}
                /* ,{field: 'jobClass', title: '任务类名', width: 235, sort: true} */
            ]]
            ,page: false
            ,request: {   //如果无需自定义请求参数，可不加该参数
                pageName: 'page' //页码的参数名称，默认：page
                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            ,response: {   //如果无需自定义数据响应名称，可不加该参数
                countName: 'total' //规定数据总数的字段名称，默认：count
                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
            }
            ,done : function(res, curr, count){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });

        

        //添加事件
        $("#add").click(function(){
            layer.open({
                type: 1 		//Page层类型
                ,area: ['585px', '400px'] //宽  高
                ,skin: 'alert-skin'
                ,title: '添加定时'
                ,shade: 0.6 	//遮罩透明度
                ,shadeClose: true //点击遮罩关闭
                ,maxmin: true //允许全屏最小化
                ,anim: 1 		//0-6的动画形式，-1不开启
                ,content: $('#addDivID')
                ,end: function () {
                    var formDiv = document.getElementById('addDivID');
                    formDiv.style.display = '';
                }
                ,success: function(){
                    $("#id").val(0)
                    $("#jobGroupName").val("");
                    $("#jobName").val("");
                    $("#jobGroupName").attr("readOnly","false");
                    $("#jobName").attr("readOnly","false");
                    $("#cronExpression").val("");
                    $("#num").val("");
                    form.render();
                }
            });
        });
        //修改事件
        $("#edit").click(function(){
            var checkStatus = table.checkStatus('LAY_table_user')
            var datas = checkStatus.data;
            if(datas.length != 1){
                toastr.warning("请选择一条记录！");
            }else{
                var data = datas[0]
                layer.open({
                    type: 1 		//Page层类型
                    ,area: ['585px', '400px'] //宽  高
                    ,skin: 'alert-skin'
                    ,title: '修改定时'
                    ,shade: 0.6 	//遮罩透明度
                    ,shadeClose: true //点击遮罩关闭
                    ,maxmin: true //允许全屏最小化
                    ,anim: 1 		//0-6的动画形式，-1不开启
                    ,content: $('#addDivID')
                    ,end: function () {
                        var formDiv = document.getElementById('addDivID');
                        formDiv.style.display = '';
                    }
                    ,success: function(){
                        $("#id").val(1)
                        $("#jobGroupName").val(data.jobGroupName);
                        $("#jobName").val(data.jobName);
                        $("#jobGroupName").attr("readOnly","true");
                        $("#jobName").attr("readOnly","true");
                        $("#cronExpression").val(data.cronExpression);
                        form.render();
                    }
                });
            }
        });
        //修改事件
        $("#reload").click(function(){
        	table.reload('LAY_table_user',{
                method:'get'
                ,page: {
                    curr: 1//重新从第 1 页开始
                }
            });
        });
        /**
		 * 新增表单校验
		 */
		form.verify({
			//value：表单的值、item：表单的DOM对象
            required: function(value, item){
            	value = $.trim(value)
            	if(value == '' || value == null){
                    return '不能为空';
                }
            },
          	//value：表单的值、item：表单的DOM对象
            cronExpression: function(value, item){
            	value = $.trim(value)
				//var regEx = "(((^([0-9]|[0-5][0-9])(\\,|\\-|\\/){1}([0-9]|[0-5][0-9]) )|^([0-9]|[0-5][0-9]) |^(\\* ))((([0-9]|[0-5][0-9])(\\,|\\-|\\/){1}([0-9]|[0-5][0-9]) )|([0-9]|[0-5][0-9]) |(\\* ))((([0-9]|[01][0-9]|2[0-3])(\\,|\\-|\\/){1}([0-9]|[01][0-9]|2[0-3]) )|([0-9]|[01][0-9]|2[0-3]) |(\\* ))((([0-9]|[0-2][0-9]|3[01])(\\,|\\-|\\/){1}([0-9]|[0-2][0-9]|3[01]) )|(([0-9]|[0-2][0-9]|3[01]) )|(\\? )|(\\* )|(([1-9]|[0-2][0-9]|3[01])L )|([1-7]W )|(LW )|([1-7]\\#[1-4] ))((([1-9]|0[1-9]|1[0-2])(\\,|\\-|\\/){1}([1-9]|0[1-9]|1[0-2]) )|([1-9]|0[1-9]|1[0-2]) |(\\* ))(([1-7](\\,|\\-|\\/){1}[1-7])|([1-7])|(\\?)|(\\*)|(([1-7]L)|([1-7]\\#[1-4]))))|(((^([0-9]|[0-5][0-9])(\\,|\\-|\\/){1}([0-9]|[0-5][0-9]) )|^([0-9]|[0-5][0-9]) |^(\\* ))((([0-9]|[0-5][0-9])(\\,|\\-|\\/){1}([0-9]|[0-5][0-9]) )|([0-9]|[0-5][0-9]) |(\\* ))((([0-9]|[01][0-9]|2[0-3])(\\,|\\-|\\/){1}([0-9]|[01][0-9]|2[0-3]) )|([0-9]|[01][0-9]|2[0-3]) |(\\* ))((([0-9]|[0-2][0-9]|3[01])(\\,|\\-|\\/){1}([0-9]|[0-2][0-9]|3[01]) )|(([0-9]|[0-2][0-9]|3[01]) )|(\\? )|(\\* )|(([1-9]|[0-2][0-9]|3[01])L )|([1-7]W )|(LW )|([1-7]\\#[1-4] ))((([1-9]|0[1-9]|1[0-2])(\\,|\\-|\\/){1}([1-9]|0[1-9]|1[0-2]) )|([1-9]|0[1-9]|1[0-2]) |(\\* ))(([1-7](\\,|\\-|\\/){1}[1-7] )|([1-7] )|(\\? )|(\\* )|(([1-7]L )|([1-7]\\#[1-4]) ))((19[789][0-9]|20[0-9][0-9])\\-(19[789][0-9]|20[0-9][0-9])))";
            	/* var regEx = /^[0-9]\d*$/;
            	if(value != '' && value != null && !regEx.test(value)){ */
            	var isTrue = cronValidate(value)
            	if(value == '' || value == null){
                    return '不能为空';
                }else if(value != '' && value != null && !isTrue){
                    return '请输入正确的cron表达式';
                }
            }
		});
        /**
         * 通用表单提交(AJAX方式)(新增)
         */
        form.on('submit(addForm)', function (data) {
            var index = layer.load(1, {
                shade: [0.1,'#000'] //0.1透明度的背景
            });
            var id = $("#id").val()

            var jobGroupName = $("#jobGroupName").val();
            var jobName = $("#jobName").val();
            var cronExpression = $("#cronExpression").val();
            if(id == 1){
                $.ajax({
                    type:'post',
                    url:'${pageContext.request.contextPath }/systemTask/updataTaskCronByTriggerNameAndTriggerGroupName.do',
                    data:{"triggerName":jobName,"triggerGroupName":jobGroupName,"cron":cronExpression},
                    success:function(data){
                        if(data>0){
                            toastr.success("修改成功！");
                            table.reload('LAY_table_user',{
                                method:'get'
                                ,page: {
                                    curr: 1//重新从第 1 页开始
                                }
                            });
                            layer.closeAll();
                        }else{
                            toastr.warning("修改失败！");
                        }
                    }

                })
            }else if(id == 0){
                $.ajax({
                    type:'post',
                    url:'${pageContext.request.contextPath }/systemTask/sendQQMail.do',
                    data:{"triggerName":jobName,"triggerGroupName":jobGroupName,"cron":cronExpression},
                    success:function(data){
                        if(data>0){
                            toastr.success("添加成功！");
                            table.reload('LAY_table_user',{
                                method:'get'
                                ,page: {
                                    curr: 1//重新从第 1 页开始
                                }
                            });
                            layer.closeAll();
                        }else{
                            toastr.warning("添加失败！");
                        }
                    }

                })
            }
            layer.close(index);
            return false;
        });
    });


    Date.prototype.format = function(fmt) {
        var o = {
            "M+" : this.getMonth() + 1, //月份
            "d+" : this.getDate(), //日
            "h+" : this.getHours(), //小时
            "m+" : this.getMinutes(), //分
            "s+" : this.getSeconds(), //秒
            "q+" : Math.floor((this.getMonth() + 3) / 3), //季度
            "S" : this.getMilliseconds()
            //毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for ( var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }

    toastrStyle()
    
    
        /**
     * Validates a cron expression.
     *
     * @param cronExpression The expression to validate
     * @return True is expression is valid
     */
    function cronValidate(cronExpression ){
        //alert("校验函数的开始！");
        var cronParams = cronExpression.split(" ");
 
        if (cronParams.length < 6 || cronParams.length > 7) {
            return false;
        }
 
        //CronTrigger cronTrigger = new CronTrigger();
        //cronTrigger.setCronExpression( cronExpression );
 
        if (cronParams[3] == "?" || cronParams[5]=="?") {
            //Check seconds param
            if (!checkSecondsField(cronParams[0])) {
                return false;
            }
 
            //Check minutes param
            if (!checkMinutesField(cronParams[1])) {
                return false;
            }
 
            //Check hours param
            if (!checkHoursField(cronParams[2])) {
                return false;
            }
 
            //Check day-of-month param
            if (!checkDayOfMonthField(cronParams[3])) {
                return false;
            }
 
            //Check months param
            if (!checkMonthsField(cronParams[4])) {
                return false;
            }
 
            //Check day-of-week param
            if (!checkDayOfWeekField(cronParams[5])) {
                return false;
            }
 
            //Check year param
            if (cronParams.length == 7) {
                if (!checkYearField(cronParams[6])) {
                    return false;
                }
            }
 
            return true;
        } else {
            return false;
        }
    }
 
    function checkSecondsField(secondsField) {
        return checkField(secondsField, 0, 59);
    }
 
 
    function checkField(secondsField, minimal, maximal) {
        if (secondsField.indexOf("-") > -1 ) {
            var startValue = secondsField.substring(0, secondsField.indexOf( "-" ));
            var endValue = secondsField.substring(secondsField.indexOf( "-" ) + 1);
 
            if (!(checkIntValue(startValue, minimal, maximal, true) && checkIntValue(endValue, minimal, maximal, true))) {
                return false;
            }
            try {
                var startVal = parseInt(startValue, 10);
                var endVal = parseInt(endValue, 10);
 
                return endVal > startVal;
            } catch (e) {
                return false;
            }
        } else if (secondsField.indexOf(",") > -1) {
            return checkListField(secondsField, minimal, maximal);
        } else if (secondsField.indexOf( "/" ) > -1) {
            return checkIncrementField( secondsField, minimal, maximal );
        } else if (secondsField.indexOf( "*" ) != -1) {
            return true;
        } else {
            return checkIntValue(secondsField, minimal, maximal);
        }
    }
 
    function checkIntValue(value, minimal, maximal, checkExtremity) {
        try {
            var val = parseInt(value, 10);
            //判断是否为整数
            if (value == val) {
                if (checkExtremity) {
                    if (val < minimal || val > maximal) {
                        return false;
                    }
                }
 
                return true;
            }
 
            return false;
        } catch (e) {
            return false;
        }
    }
 
    function checkMinutesField(minutesField) {
        return checkField(minutesField, 0, 59);
    }
 
    function checkHoursField(hoursField) {
        return checkField(hoursField, 0, 23);
    }
 
    function checkDayOfMonthField(dayOfMonthField) {
        if (dayOfMonthField == "?") {
            return true;
        }
 
        if (dayOfMonthField.indexOf("L") >= 0) {
            return checkFieldWithLetter(dayOfMonthField, "L", 1, 7, -1, -1);
        } else if ( dayOfMonthField.indexOf("W") >= 0) {
            return checkFieldWithLetter(dayOfMonthField, "W", 1, 31, -1, -1);
        } else if (dayOfMonthField.indexOf("C") >= 0) {
            return checkFieldWithLetter(dayOfMonthField, "C", 1, 31, -1, -1);
        } else {
            return checkField( dayOfMonthField, 1, 31 );
        }
    }
 
 
    function checkMonthsField(monthsField) {
/*        monthsField = StringUtils.replace( monthsField, "JAN", "1" );
        monthsField = StringUtils.replace( monthsField, "FEB", "2" );
        monthsField = StringUtils.replace( monthsField, "MAR", "3" );
        monthsField = StringUtils.replace( monthsField, "APR", "4" );
        monthsField = StringUtils.replace( monthsField, "MAY", "5" );
        monthsField = StringUtils.replace( monthsField, "JUN", "6" );
        monthsField = StringUtils.replace( monthsField, "JUL", "7" );
        monthsField = StringUtils.replace( monthsField, "AUG", "8" );
        monthsField = StringUtils.replace( monthsField, "SEP", "9" );
        monthsField = StringUtils.replace( monthsField, "OCT", "10" );
        monthsField = StringUtils.replace( monthsField, "NOV", "11" );
        monthsField = StringUtils.replace( monthsField, "DEC", "12" );*/
 
        monthsField.replace("JAN", "1");
        monthsField.replace("FEB", "2");
        monthsField.replace("MAR", "3");
        monthsField.replace("APR", "4");
        monthsField.replace("MAY", "5");
        monthsField.replace("JUN", "6");
        monthsField.replace("JUL", "7");
        monthsField.replace("AUG", "8");
        monthsField.replace("SEP", "9");
        monthsField.replace("OCT", "10");
        monthsField.replace("NOV", "11");
        monthsField.replace("DEC", "12");
 
        return checkField(monthsField, 1, 31);
    }
 
    function checkDayOfWeekField(dayOfWeekField) {
/*        dayOfWeekField = StringUtils.replace( dayOfWeekField, "SUN", "1" );
        dayOfWeekField = StringUtils.replace( dayOfWeekField, "MON", "2" );
        dayOfWeekField = StringUtils.replace( dayOfWeekField, "TUE", "3" );
        dayOfWeekField = StringUtils.replace( dayOfWeekField, "WED", "4" );
        dayOfWeekField = StringUtils.replace( dayOfWeekField, "THU", "5" );
        dayOfWeekField = StringUtils.replace( dayOfWeekField, "FRI", "6" );
        dayOfWeekField = StringUtils.replace( dayOfWeekField, "SAT", "7" );*/
 
        dayOfWeekField.replace("SUN", "1" );
        dayOfWeekField.replace("MON", "2" );
        dayOfWeekField.replace("TUE", "3" );
        dayOfWeekField.replace("WED", "4" );
        dayOfWeekField.replace("THU", "5" );
        dayOfWeekField.replace("FRI", "6" );
        dayOfWeekField.replace("SAT", "7" );        
 
        if (dayOfWeekField == "?") {
            return true;
        }
 
        if (dayOfWeekField.indexOf("L") >= 0) {
            return checkFieldWithLetter(dayOfWeekField, "L", 1, 7, -1, -1);
        } else if (dayOfWeekField.indexOf("C") >= 0) {
            return checkFieldWithLetter(dayOfWeekField, "C", 1, 7, -1, -1);
        } else if (dayOfWeekField.indexOf("#") >= 0) {
            return checkFieldWithLetter(dayOfWeekField, "#", 1, 7, 1, 5);
        } else {
            return checkField(dayOfWeekField, 1, 7);
        }
    }
 
    function checkYearField(yearField) {
        return checkField(yearField, 1970, 2099);
    }
 
 
    function checkFieldWithLetter(value, letter, minimalBefore, maximalBefore,
                                          minimalAfter, maximalAfter) {
        var canBeAlone = false;
        var canHaveIntBefore = false;
        var canHaveIntAfter = false;
        var mustHaveIntBefore = false;
        var mustHaveIntAfter = false;
 
        if (letter == "L") {
            canBeAlone = true;
            canHaveIntBefore = true;
            canHaveIntAfter = false;
            mustHaveIntBefore = false;
            mustHaveIntAfter = false;
        }
        if (letter == "W" || letter == "C") {
            canBeAlone = false;
            canHaveIntBefore = true;
            canHaveIntAfter = false;
            mustHaveIntBefore = true;
            mustHaveIntAfter = false;
        }
        if (letter == "#") {
            canBeAlone = false;
            canHaveIntBefore = true;
            canHaveIntAfter = true;
            mustHaveIntBefore = true;
            mustHaveIntAfter = true;
        }
 
        var beforeLetter = "";
        var afterLetter = "";
 
        if (value.indexOf(letter) >= 0 ) {
            beforeLetter = value.substring( 0, value.indexOf(letter));
        }
 
        if (!value.endsWith(letter)) {
            afterLetter = value.substring( value.indexOf( letter ) + 1 );
        }
 
        if (value.indexOf(letter) >= 0) {
            if (letter == value) {
                return canBeAlone;
            }
 
            if (canHaveIntBefore) {
                if (mustHaveIntBefore && beforeLetter.length == 0) {
                    return false;
                }
 
                if (!checkIntValue(beforeLetter, minimalBefore, maximalBefore, true)){
                    return false;
                }
            } else {
                if (beforeLetter.length > 0 ) {
                    return false;
                }
            }
 
            if (canHaveIntAfter) {
                if ( mustHaveIntAfter && afterLetter.length == 0 ) {
                    return false;
                }
 
                if (!checkIntValue(afterLetter, minimalAfter, maximalAfter, true)) {
                    return false;
                }
            } else {
                if (afterLetter.length > 0) {
                    return false;
                }
            }
        }
 
        return true;
    }
 
/*    function checkIntValue(value, minimal, maximal) {
        return checkIntValue(value, minimal, maximal, true);
    } */
 
    function checkIncrementField(value, minimal, maximal) {
        var start = value.substring(0, value.indexOf("/"));
 
        var increment = value.substring(value.indexOf("/") + 1);
 
        if (!("*" == start)) {
            return checkIntValue(start, minimal, maximal, true) && checkIntValue(increment, minimal, maximal, false);
        } else {
            return checkIntValue(increment, minimal, maximal, true);
        }
    }
 
 
 
    function checkListField(value, minimal, maximal ) {
        var st = value.split(",");
 
        var values = new Array(st.length);
 
        for(var j = 0; j < st.length; j++) {
            values[j] = st[j];
        }
 
        var previousValue = -1;
 
        for (var i= 0; i < values.length; i++) {
            var currentValue = values[i];
 
            if (!checkIntValue(currentValue, minimal, maximal, true)) {
                return false;
            }
 
            try {
                var val = parseInt(currentValue, 10);
 
                if (val <= previousValue) {
                    return false;
                } else {
                    previousValue = val;
                }
            } catch (e) {
                // we have always an int
            }
        }
 
        return true;
    }

</script>

</body>
</html>
